<?php 

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';
	
	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";

	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];
	
	// get game id from url hash
	if(isset($_GET['id']) && $_GET['id'] != '') {
		
		// validate and sanitize game id
		if(filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
			
			$g_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
			
			// gather game info 
			$sql = "SELECT games.date, games.start_time, games.away_team, CONCAT(t1.city, ' ', t1.name) AS 'away', games.home_team, CONCAT(t2.city, ' ', t2.name) AS 'home', game_details.inning_half, game_details.inning_number, game_details.away_roster, game_details.home_roster, game_details.away_runs, game_details.away_hits, game_details.away_errors, game_details.home_runs, game_details.home_hits, game_details.home_errors, game_details.attendance, users.name FROM games LEFT JOIN game_details ON games.game_id = game_details.game_id LEFT JOIN teams AS t1 ON t1.team_id = games.away_team LEFT JOIN teams AS t2 ON t2.team_id = games.home_team LEFT JOIN users ON users.user_id = games.user_id WHERE games.game_id = " . $g_id;
						
			try {
				
				$stmt = $db->prepare($sql);
				$stmt->execute();
								
				// bind column names
				$stmt->bindColumn(1, $date);
				$stmt->bindColumn(2, $start_time);
				$stmt->bindColumn(3, $a_team_id);
				$stmt->bindColumn(4, $away_team);
				$stmt->bindColumn(5, $h_team_id);
				$stmt->bindColumn(6, $home_team);
				$stmt->bindColumn(7, $inning_half);
				$stmt->bindColumn(8, $inning_number);
				$stmt->bindColumn(9, $away_roster);
				$stmt->bindColumn(10, $home_roster);
				$stmt->bindColumn(11, $a_runs);
				$stmt->bindColumn(12, $a_hits);
				$stmt->bindColumn(13, $a_errors);
				$stmt->bindColumn(14, $h_runs);
				$stmt->bindColumn(15, $h_hits);
				$stmt->bindColumn(16, $h_errors);
				$stmt->bindColumn(17, $attendance);
				$stmt->bindColumn(18, $user_name);
				
				$stmt->fetch(PDO::FETCH_BOUND);
				
			} catch(PDOException $e) {
				
				$message[] = '<p class="error">DB Error: ' . $e->getMessage() . '</p>';
				$error = true;
				
			}
			
		}else{
			
			// invalid game id
			header("Location: http://localhost/atbat/html/new-game");	
			
		}
		
	}else{
		
		// no id in url hash
		header("Location: http://localhost/atbat/html/new-game");	
		
	}
	
	// process game scoring
	if(isset($_POST['score_game'])) {
		
		// sanitize and validate data
		$error = false;
		
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Score a New Game</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css"><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<h1>Scorecard</h1>
        <?php if(isset($message)) foreach($message as $m) print $m; ?>
        <!-- game details -->
        <table id="gameDetails" cellpadding="0" cellspacing="0" summary="Show game details such as date, time and weather">
        	<tr>
            	<th>Date:</th>
                <th><?php echo date('m-d-Y', strtotime($date)); ?></th>
                <th>Scorer:</th>
                <th><?php echo $user_name; ?></th>
                <th>Attendance:</th>
                <th><?php echo $attendance; ?></th>
            </tr>
            <tr>
            	<th>Start Time:</th>
                <th id="startTime"><?php echo date('g:i', strtotime($start_time)); ?></th>
                <th>End Time:</th>
                <th contenteditable="true" title="Enter End Time Here" id="endTime"> </th>
            	<th>Length of Game:</th>
                <th contenteditable="true" title="Enter Game Length Here" id="gameLength"> </th>
            </tr>
        </table>
        <!-- box score -->
        <table id="boxScore" cellpadding="0" cellspacing="0" summary="Box score for this game">
        	<tr>
            	<th>Teams</th>
                <th>1</th>
                <th>2</th>
                <th>3</th>
                <th>4</th>
                <th>5</th>
                <th>6</th>
                <th>7</th>
                <th>8</th>
                <th>9</th>
                <th>10</th>
                <th>R</th>
                <th>H</th>
                <th>E</th>
            </tr>
            <tr id="awayBoxScore">
            	<td><?php echo $away_team; ?></td>
                <td id="away_1" class="currentInning">0</td>
                <td id="away_2">0</td>
                <td id="away_3">0</td>
                <td id="away_4">0</td>
                <td id="away_5">0</td>
                <td id="away_6">0</td>
                <td id="away_7">0</td>
                <td id="away_8">0</td>
                <td id="away_9">0</td>
                <td id="away_10">0</td>
                <td id="away_R">0</td>
                <td id="away_H">0</td>
                <td id="away_E">0</td>
            </tr>
            <tr id="homeBoxScore">
            	<td><?php echo $home_team; ?></td>
                <td id="home_1">0</td>
                <td id="home_2">0</td>
                <td id="home_3">0</td>
                <td id="home_4">0</td>
                <td id="home_5">0</td>
                <td id="home_6">0</td>
                <td id="home_7">0</td>
                <td id="home_8">0</td>
                <td id="home_9">0</td>
                <td id="home_10">0</td>
                <td id="home_R">0</td>
                <td id="home_H">0</td>
                <td id="home_E">0</td>
            </tr>
        </table>
        <!-- players and at bats -->
    	<form method="post" action="score-game">
        	<table id="scorecardAway" cellpadding="0" cellspacing="0" summary="Line up and diagrams of each at bat">
            	<tr>
                	<th>#</th>
                    <th>Player</th>
                    <th>Pos</th>
                    <th>1</th>
                    <th>2</th>
                    <th>3</th>
                    <th>4</th>
                    <th>5</th>
                    <th>6</th>
                    <th>7</th>
                    <th>8</th>
                    <th>9</th>
                    <th>10</th>
                    <!-- larger screens could get extra columns for at bat totals -->
                </tr>
                <?php
				
					// loop through roster and create table
					$j = 1;
					
					// show away or home team based on inning half with CSS
					$away = "SELECT players.player_id, players.name, players.position, players.number FROM players LEFT JOIN rosters_players ON rosters_players.player_id = players.player_id LEFT JOIN batting_order ON batting_order.player_id = rosters_players.player_id LEFT JOIN game_details ON game_details.away_roster = rosters_players.roster_id WHERE game_details.away_roster = " . $away_roster . " GROUP BY players.player_id ORDER BY batting_order.batting_order";
						
					foreach($db->query($away) as $row) {
						
				?>
                <tr id="player_<?php echo $row[0]; ?>">
                	<!-- TODO: this will need ability to add sub players -->
                    <td><?php echo $row[3]; ?></td>
                	<td><?php echo $row[1]; ?></td>
                    <td><?php echo $row[2]; ?></td>
                    <?php for($i = 1; $i <= 10; $i++) { ?>
                    <td class="atbat" id="<?php echo $j; ?>" rel="<?php echo $row[0]; ?>"></td>
                    <?php 
						
						$j++;
						
					} ?>
                </tr>
                <?php } ?>
                <tr>
                	<th rowspan="4">Totals</th>
                    <th colspan="2">Runs</th>
                    <td id="inningOneTotalRuns"></td>
                    <td id="inningTwoTotalRuns"></td>
                    <td id="inningThreeTotalRuns"></td>
                    <td id="inningFourTotalRuns"></td>
                    <td id="inningFiveTotalRuns"></td>
                    <td id="inningSixTotalRuns"></td>
                    <td id="inningSevenTotalRuns"></td>
                    <td id="inningEightTotalRuns"></td>
                    <td id="inningNineTotalRuns"></td>
                    <td id="inningTenTotalRuns"></td>
                </tr>
                <tr>
                    <th colspan="2">Hits</th>
                    <td id="inningOneTotalHits"></td>
                    <td id="inningTwoTotalHits"></td>
                    <td id="inningThreeTotalHits"></td>
                    <td id="inningFourTotalHits"></td>
                    <td id="inningFiveTotalHits"></td>
                    <td id="inningSixTotalHits"></td>
                    <td id="inningSevenTotalHits"></td>
                    <td id="inningEightTotalHits"></td>
                    <td id="inningNineTotalHits"></td>
                    <td id="inningTenTotalHits"></td>
                </tr>
                <tr>
                    <th colspan="2">Errors</th>
                    <td id="inningOneTotalErrors"></td>
                    <td id="inningTwoTotalErrors"></td>
                    <td id="inningThreeTotalErrors"></td>
                    <td id="inningFourTotalErrors"></td>
                    <td id="inningFiveTotalErrors"></td>
                    <td id="inningSixTotalErrors"></td>
                    <td id="inningSevenTotalErrors"></td>
                    <td id="inningEightTotalErrors"></td>
                    <td id="inningNineTotalErrors"></td>
                    <td id="inningTenTotalErrors"></td>
                </tr>
                <tr>
                    <th colspan="2">LeftonBase</th>
                    <td id="inningOneTotalLeftonBase"></td>
                    <td id="inningTwoTotalLeftonBase"></td>
                    <td id="inningThreeTotalLeftonBase"></td>
                    <td id="inningFourTotalLeftonBase"></td>
                    <td id="inningFiveTotalLeftonBase"></td>
                    <td id="inningSixTotalLeftonBase"></td>
                    <td id="inningSevenTotalLeftonBase"></td>
                    <td id="inningEightTotalLeftonBase"></td>
                    <td id="inningNineTotalLeftonBase"></td>
                    <td id="inningTenTotalLeftonBase"></td>
                </tr>
            </table>
            <!-- home team -->
            <table id="scorecardHome" class="hidden" cellpadding="0" cellspacing="0" summary="Line up and diagrams of each at bat">
            	<tr>
                	<th>#</th>
                    <th>Player</th>
                    <th>Pos</th>
                    <th>1</th>
                    <th>2</th>
                    <th>3</th>
                    <th>4</th>
                    <th>5</th>
                    <th>6</th>
                    <th>7</th>
                    <th>8</th>
                    <th>9</th>
                    <th>10</th>
                    <!-- larger screens could get extra columns for at bat totals -->
                </tr>
                <?php
				
					// loop through roster and create table					
					// show away or home team based on inning half with CSS
					$home = "SELECT players.player_id, players.name, players.position, players.number FROM players LEFT JOIN rosters_players ON rosters_players.player_id = players.player_id LEFT JOIN batting_order ON batting_order.player_id = rosters_players.player_id LEFT JOIN game_details ON game_details.home_roster = rosters_players.roster_id WHERE game_details.home_roster = " . $home_roster . " GROUP BY players.player_id ORDER BY batting_order.batting_order";
						
					foreach($db->query($home) as $row) {
						
				?>
                <tr id="player_<?php echo $row[0]; ?>">
                	<!-- TODO: this will need ability to add sub players -->
                    <td><?php echo $row[3]; ?></td>
                	<td><?php echo $row[1]; ?></td>
                    <td><?php echo $row[2]; ?></td>
                    <?php for($i = 1; $i <= 10; $i++) { ?>
                    <td class="atbat" id="<?php echo $j; ?>" rel="<?php echo $row[0]; ?>"></td>
                    <?php 
						
						$j++;
						
					} ?>
                </tr>
                <?php } ?>
                <tr>
                	<th rowspan="4">Totals</th>
                    <th colspan="2">Runs</th>
                    <td id="inningOneTotalRuns"></td>
                    <td id="inningTwoTotalRuns"></td>
                    <td id="inningThreeTotalRuns"></td>
                    <td id="inningFourTotalRuns"></td>
                    <td id="inningFiveTotalRuns"></td>
                    <td id="inningSixTotalRuns"></td>
                    <td id="inningSevenTotalRuns"></td>
                    <td id="inningEightTotalRuns"></td>
                    <td id="inningNineTotalRuns"></td>
                    <td id="inningTenTotalRuns"></td>
                </tr>
                <tr>
                    <th colspan="2">Hits</th>
                    <td id="inningOneTotalHits"></td>
                    <td id="inningTwoTotalHits"></td>
                    <td id="inningThreeTotalHits"></td>
                    <td id="inningFourTotalHits"></td>
                    <td id="inningFiveTotalHits"></td>
                    <td id="inningSixTotalHits"></td>
                    <td id="inningSevenTotalHits"></td>
                    <td id="inningEightTotalHits"></td>
                    <td id="inningNineTotalHits"></td>
                    <td id="inningTenTotalHits"></td>
                </tr>
                <tr>
                    <th colspan="2">Errors</th>
                    <td id="inningOneTotalErrors"></td>
                    <td id="inningTwoTotalErrors"></td>
                    <td id="inningThreeTotalErrors"></td>
                    <td id="inningFourTotalErrors"></td>
                    <td id="inningFiveTotalErrors"></td>
                    <td id="inningSixTotalErrors"></td>
                    <td id="inningSevenTotalErrors"></td>
                    <td id="inningEightTotalErrors"></td>
                    <td id="inningNineTotalErrors"></td>
                    <td id="inningTenTotalErrors"></td>
                </tr>
                <tr>
                    <th colspan="2">LeftonBase</th>
                    <td id="inningOneTotalLeftonBase"></td>
                    <td id="inningTwoTotalLeftonBase"></td>
                    <td id="inningThreeTotalLeftonBase"></td>
                    <td id="inningFourTotalLeftonBase"></td>
                    <td id="inningFiveTotalLeftonBase"></td>
                    <td id="inningSixTotalLeftonBase"></td>
                    <td id="inningSevenTotalLeftonBase"></td>
                    <td id="inningEightTotalLeftonBase"></td>
                    <td id="inningNineTotalLeftonBase"></td>
                    <td id="inningTenTotalLeftonBase"></td>
                </tr>
            </table>
            <a href="#" id="inningSave">Save Inning</a>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script>
    	$(document).ready(function() {	
			// TODO: correct the formatting of the game length time
			// update game length when user enters end time
			$("#endTime").blur(function() {
				localStorage.setItem("endTime", $(this).text());
				var startTime = new Date("January 1, 2011 " + $("#startTime").text() + ":00");
				var endTime = new Date("January 1, 2011 " + localStorage.getItem("endTime") + ":00");
				var gameLength = new Date();
				
				gameLength.setTime(endTime - startTime);
				var length = gameLength.getHours() + ":" + gameLength.getMinutes();
				$("#gameLength").text(length);
				alert(length);
			});
			
			// show/hide away/home team tables based on inning half
			// this will save inning half data 
			// may get moved elsewhere in the template or could
			// be automatic based on results of each at bat in the inning
			$("#inningSave").click(function() {
											
				$("#scorecardAway").toggleClass('hidden');
				$("#scorecardHome").toggleClass('hidden');
				
				return false;
											
			});
			
			// show version 1 at bat scoring box
			$("td.atbat").click(function() {
				$("#dialog-atbat").data(
					"atbat", 
					{ 
						ab_id: $(this).attr("id"), 
						p_id: $(this).attr("rel")
					}
				).dialog("open");							 
			});
			
			$("#dialog-atbat").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Save At Bat": function() {
						$.post(
							"save-atbat.php",
							{
								ab_id: $(this).data("atbat").ab_id,
								p_id: $(this).data("atbat").p_id,
								g_id: <?php echo $g_id; ?>,
								balls: $("#balls").val(),
								strikes: $("#strikes").val(),
								play: $("#play").val(),
								rbi: $("#rbi").val(),
								saveAB: 1
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialog-atbat").prepend(data);
								if($(data).hasClass('success')) {
									// close window after 5 seconds on success
									setTimeout(function() { 
										$("#dialog-atbat").dialog("close");
									}, 2500);
									
									// clear input fields
									$("#balls").val(0);
									$("#strikes").val(0);
									$("#play").val('');
									$("#rbi").val(0);
								}
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
		});
    </script>
    <fieldset id="dialog-atbat" title="Score This Play">
    	<p><label for="balls">Balls:</label><input type="number" name="balls" id="balls" required value="0" min="0" max="4" step="1" /></p>
        <p><label for="strikes">Strikes:</label><input type="number" name="strikes" id="strikes" required value="0" min="0" max="3" step="1" /></p>
        <p><label for="play">Play:</label><input type="text" name="play" id="play" required /></p>
        <p><label for="rbi">RBI:</label><input type="number" name="rbi" id="rbi" required value="0" min="0" max="4" step="1" /></p>
    </fieldset>
</body>
</html>